package com.grape.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grape.domain.AccountBook;
import com.grape.domain.Category;
import com.grape.domain.CategorySetting;
import com.grape.mapper.CategoryMapper;
import com.grape.service.ICategoryService;
import com.grape.service.ICategorySettingService;
import com.grape.constants.Constants;
import com.grape.dto.CategoryBudgetDTO;
import com.grape.utils.StringUtils;
import com.grape.utils.ThreadLocalUtil;
import com.grape.vo.BaseVo;
import com.grape.wrapper.BaseWrapper;
import com.grape.utils.DateUtils;
import lombok.AllArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 *
 * 分类表 服务实现类
 *
 * @author      putao
 * @email       2628279194@qq.com
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    private final CategoryMapper categoryMapper;

    private final ICategorySettingService categorySettingService;

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(CategoryServiceImpl.class);

    /**
     * 分页
     * @param baseVo    统一分页对象
     * @return          分类表集合
     */
    @Override
    public List<Category> listData(BaseVo baseVo) {
        QueryWrapper<Category> wrapper = new BaseWrapper<Category>().init();
        wrapper.like(Strings.isNotBlank(baseVo.getSearch()), Constants.NAME, baseVo.getSearch())
                .eq(StringUtils.isNotBlank(baseVo.getColumnName()) && StringUtils.isNotBlank(baseVo.getSelect()), baseVo.getColumnName(), baseVo.getSelect());
        orderByModifyTimeDesc(wrapper);
        return this.list(wrapper);
    }

    /**
     * 自定义分页
     * @param   baseVo      统一分页对象
     */
    @Override
    public void pageListCustom(BaseVo baseVo) {
        String userId = ThreadLocalUtil.getUserId();
        QueryWrapper<Category> qw = new QueryWrapper<Category>().eq(Constants.USER_ID, userId)
                .orderByDesc(Constants.CREATE_TIME);
        this.categoryMapper.selectList(qw);
    }

    /**
     * 修改
     * @param category 分类表对象
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void updateData(Category category) {
        this.checkIsRepeat(w -> w.eq(Constants.TYPE, category.getType()), category, Constants.NAME, MessageFormat.format("分类名字：{0} 已存在", category.getName()));
        this.baseUpdate(category);
    }

    /**
     * 新增
     * @param       category 分类表对象
     * @return      分类表对象
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Category insertData(Category category) {
        category.setUserId(ThreadLocalUtil.getUserId());
        this.checkIsRepeat(w -> w.eq(Constants.TYPE, category.getType()), category, Constants.NAME, MessageFormat.format("分类名字：{0} 已存在", category.getName()));
        return this.baseInsert(category);
    }

    /**
     * 删除
     * @param id    单据id
     * @return      删除条数
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public int deleteData(String id) {
        return this.baseDelete(id);
    }

    /**
     * 根据id查询详情
     * @param       id  单据id
     * @return      分类表对象
     */
    @Override
    public Category detail(String id) {
        return this.getByIdForDelFlag(id);
    }

    /**
     * 查询当前用户全部分类
     * accountBookId   账本id
     * @return 分类列表
     */
    @Override
    public List<Category> listAll(String accountBookId) {
        return categoryMapper.selectList(new BaseWrapper<Category>().initDelFlagAndUserId().eq(StringUtils.isNotBlank(accountBookId), Constants.ACCOUNT_BOOK_ID, accountBookId));
    }

    /**
     * 根据账本id统计分类预算
     * @param accountBookId 账本id
     * @return  分类预算
     */
    @Override
    public List<CategoryBudgetDTO> statisticBudget(String accountBookId) {
        Date date = new Date();
        List<CategoryBudgetDTO> budgetDTOList = categoryMapper.statisticBudget(accountBookId, DateUtils.getFirstDayOfMonth(date), DateUtils.getNextMonthFirstDay(date), ThreadLocalUtil.getUserId());
        if (CollectionUtil.isEmpty(budgetDTOList)) {
            return Collections.emptyList();
        }
        for (CategoryBudgetDTO dto : budgetDTOList) {
            dto.initField();
        }
        return budgetDTOList;
    }

    /**
     * 插入默认分类
     * @param accountBook 账本对象
     * @param userId 用户id
     */
    @Override
    public void insertDefaultData(AccountBook accountBook, String userId) {
        List<CategorySetting> categorySettings = categorySettingService.listAppendDelFlag();
        if (CollectionUtil.isEmpty(categorySettings)) {
            return;
        }
        List<Category> categoryList = new ArrayList<>();
        for (CategorySetting setting : categorySettings) {
            Category category = new Category();
            category.setUserId(userId);
            category.setName(setting.getName());
            category.setIcon(setting.getIcon());
            category.setType(setting.getType());
            category.setAppIcon(setting.getAppIcon());
            category.setAccountBookId(accountBook.getId());
            if (Constants.CATEGORY_TYPE_PAY.equals(category.getType())) {
                category.setBudget(new BigDecimal("1000"));
            }
            category.insertInit();
            categoryList.add(category);
        }
        this.saveBatch(categoryList);
    }
}
